from rest_framework_jwt.utils import jwt_payload_handler
from rest_framework_jwt.utils import jwt_response_payload_handler
from django.contrib.auth.backends import ModelBackend
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
import re
from .models import User
from rest_framework import serializers


def meiduo_payload_handler(user):
    payload = jwt_payload_handler(user)
    # 不包含邮箱
    if 'email' in payload:
        del payload['email']
    # 添加手机号
    # payload['mobile'] = user.mobile
    return payload


def meiduo_response_payload_handler(token, user=None, request=None):
    return {
        'token': token,
        'user_id': user.id,
        'username': user.username
    }


class MeiduoModelBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        # 判断username是用户名，还是手机号，做不同的查询
        if re.match(r'^1[3-9]\d{9}$', username):
            # 手机号
            try:
                user = User.objects.get(mobile=username)
            except:
                raise serializers.ValidationError('手机号错误')
        else:
            # 用户名
            try:
                user = User.objects.get(username=username)
            except:
                raise serializers.ValidationError('用户名错误')
        # 验证密码
        if user.check_password(password):
            return user
        else:
            raise serializers.ValidationError('密码错误')
